<?php
namespace Kuoqi;

/**
 * Class Openssl
 * @package Kuoqi
 * User kuoqi
 * Datetime 2022/3/3 9:33
 * Remark openssl 模块基本操作
 */
class Openssl{

    /**
     * @var string
     * User kuoqi
     * Datetime 2022/3/3 9:38
     * Remark 非空初始化向量。
     */
    const OPENSSL_RAW_DATA = OPENSSL_RAW_DATA;
    const OPENSSL_ZERO_PADDING = OPENSSL_ZERO_PADDING;

    static public $OPENSSL_IV = '';
    static public $OPENSSL_METHOD = 'AES-128-CBC';//初始化加密请求方式
    static public $OPENSSL_PASSWORD = null;

    static public function __initialize(){
        self::$OPENSSL_IV = Config::get('OPENSSL_IV');
        self::$OPENSSL_METHOD = Config::get('OPENSSL_METHOD');
        self::$OPENSSL_PASSWORD = Config::get('OPENSSL_PASSWORD');
    }

    /**
     * @param $code 待加密的数据字符串
     * @param string $method 加密方式
     * @param null $password 加密秘钥
     * @param string $iv 加密偏移向量
     * @param int $options 额外参数
     * @return string 加密之后的秘钥串
     * User kuoqi
     * Datetime 2022/3/3 10:04
     * Remark 简单加密
     */
    static public function encode($code,$method = '',$password = null,$iv = '',$options = 0){
        return openssl_encrypt(
            $code,
            self::initMethod($method),
            $password,
            $options,//OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING.
            $iv?$iv:self::$OPENSSL_IV
        );
    }

    /**
     * @param $code 待解密的数据字符串
     * @param string $method 请求解密方式
     * @param null $password 请求解密秘钥
     * @param string $iv 请求偏移向量
     * @param int $options 额外参数
     * @return string 解密之后的字符串
     * User kuoqi
     * Datetime 2022/3/3 10:07
     * Remark 简单解密
     */
    public static function decode($code,$method = '',$password = null,$iv = '',$options = 0){
        return openssl_decrypt(
            $code,
            self::initMethod($method),
            $password,
            $options,//OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING.
            $iv?$iv:self::$OPENSSL_IV
        );
    }

    /**
     * @param $method
     * @return mixed
     * User kuoqi
     * Datetime 2022/3/3 9:54
     * Remark 根据method判定是否能够获取
     */
    static public function initMethod($method){
        $methods = openssl_get_cipher_methods();
        if(in_array($method,$methods)){
            return $method;
        }else{
            return self::$OPENSSL_METHOD;
        }
    }

}